package com.daffodil.util;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取地址类
 * @author yweijian
 * @date 2019年8月18日
 * @version 1.0
 */
public class AddressUtils {
	private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

	public static final String IP_URL_TAOBAO = "http://ip.taobao.com/service/getIpInfo.php";//淘宝API，貌似已不能用
	
	public static final String IP_URL_PACIFIC = "http://whois.pconline.com.cn/ipJson.jsp";//太平洋IP地址查询

	@SuppressWarnings("unchecked")
	@Deprecated
	public static String getRealAddressByIP(String ip) {
		String address = "127.0.0.1";

		if (IpUtils.internalIp(ip)) {
			return "内网IP " + ip;
		}

		String rspStr = HttpUtils.sendPost(IP_URL_TAOBAO, "ip=" + ip, "UTF-8");
		if (StringUtils.isEmpty(rspStr)) {
			log.error("获取地理位置异常 {}", ip);
			return address;
		}
		try {
			Map<String, Object> json = JacksonUtils.toJavaObject(rspStr, Map.class);
			Map<String, Object> data = JacksonUtils.getAsMap(json, "data");
			String region = JacksonUtils.getAsString(data, "region");
			String city = JacksonUtils.getAsString(data, "city");
			address = region + " " + city;
		} catch (Exception e) {
			log.error("获取地理位置异常 {}", ip);
		}
		return address;
	}
	
	@SuppressWarnings("unchecked")
	public static String getRealAddressByIP(String ip, boolean json) {
		String address = "127.0.0.1";

		if (IpUtils.internalIp(ip)) {
			return "内网IP " + ip;
		}

		String rspStr = HttpUtils.sendGet(IP_URL_PACIFIC, "ip=" + ip + "&json=" + json, "GBK");
		if (StringUtils.isEmpty(rspStr)) {
			log.error("获取地理位置异常 {}", ip);
			return address;
		}
		try {
			Map<String, Object> jsonObject = JacksonUtils.toJavaObject(rspStr, Map.class);
			address = JacksonUtils.getAsString(jsonObject, "addr");
		} catch (Exception e) {
			log.error("获取地理位置异常 {}", ip);
		}
		return address;
	}
	
}
